<?php

namespace app\common\business;

use app\common\lib\Time;
use app\common\lib\Str;
use think\facade\Cache;
use think\Exception;

class Admin
{
    public $adminObj = null;

    public function __construct()
    {
        $this->adminObj = new \app\common\model\Admin();
    }

    public function login($data)
    {

//        根据用户名和密码，查询表是否有记录
        $data['password'] = md5($data['password'] . config('common.md5_str'));
        $admin = $this->adminObj->getAdmin($data);
        if (empty($admin)) {
            throw new Exception('管理员不存在或密码错误');
        } else {
            try {
                $token = getRandStr($data['username']);
                $redisData = [
                    'id' => $admin->id,
                    'username' => $admin->username,
                ];
                try {
                    Cache::set(config('common.token_pre') . $token, $redisData, userLoginExpiresTime());
                    return ['token' => $token, 'username' => $admin->username];
                } catch (Ex $e) {
                    throw new Exception('服务器错误内部');
                }
            } catch (Ex $e) {
                throw new Exception('服务器错误内部');
            }
        }
    }

    // 退出登陆
    public function logout($id, $token)
    {
        $admin = $this->adminObj->getAdmin(['id' => $id]);
        if (empty($admin)) {
            throw new Exception('账号不存在');
        } else {
            try {
                return Cache::set(config('common.token_pre') . $token, NULL);
            } catch (Ex $e) {
                throw new Exception('服务器错误内部');
            }
        }
    }

    public function getInfo($id){
        return $this->adminObj->getAdmin(['id' => $id]);
    }
}